package com.atguigu.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;
@Component
public class OnceTokenGatewayFilterFactory  extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //每次响应之前，添加一个一次性令牌，支持uuid,jwt等各种格式
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    final ServerHttpResponse response = exchange.getResponse();
                    final HttpHeaders headers = response.getHeaders();
                    String value = config.getValue();
                    if("uuid".equalsIgnoreCase(value)){
                        value = UUID.randomUUID().toString();
                    }
                    if("jwt".equalsIgnoreCase(value)){
                        value = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJ1c2VyX2lkIjogMTIzLCAidXNlcm5hbWUiOiAiZXhhbXBsZV91c2VyIiwgImlhdCI6IDE3NDA5NjE5MTV9.8149d78f02b7c6dd55e0e879ac241fd6f5e7d65bdf2ec8180e3f60ad2a300bef";
                    }
                    headers.add(config.getName(),value);
                }));
            }
        };
    }
}
